<template>
	<view class="dispatchSheet">
		<!-- 资源调度单 -->
		<navBar title="资源调度单" goBackUrl="/subpackage-emergency/pages/resourceScheduling" @goBack="goBack">
			<!-- <view class="del" @click="getBatchDelete">移除</view> -->
		</navBar>
		<scroll-view scroll-y="true" class="scroll-box">
			<view class="content">
				<view class="header">人员调度</view>
				<view class="person">
					<view class="nav-item">
						<view class="name" style="width: 200rpx;">劳务人员</view>
						<view class="value">
							  <u--input
								class="input"
							    placeholder="请输入劳务人员数量"
								:disabled="isLaborPerson"
								v-model="laborNum"
								@blur="laborNumBlur"
							  ></u--input>
						</view>
					</view>
					<view class="nav-item" v-if="userData.length > 0">
						<view class="name">抢险人员</view>
						<view class="value personNum">{{ userData.length }}人</view>
					</view>
					<checkbox-group @change="personChange">
						<view class="col-item" v-for="value in userData" :key="value.userId">
							<label class="label">
								<view class="name">{{ value.name }}</view>
								<view class="phone">{{ value.phone }}</view>
								<checkbox :value="value.eventCostId + ''" :checked="false" class="checkbox color round"></checkbox>
							</label>
						</view>
					</checkbox-group>
				</view>
				
				<view class="header" v-if="deviceData.length > 0">设备调度</view>
				<checkbox-group @change="deviceChange">
					<view class="device" v-for="(item,index) in deviceData" :key="item.name">
						<view class="title">
							<view class="name">{{ item.name}}</view>
							<view class="value">{{ item.num }}</view>
						</view>
					
						<label class="label" v-for="(value,idx) in item.children" :key="idx">
							<view class="coll">
								<view class="coll-item">
									<view class="name">规格型号： </view>
									<view class="value model">{{ value.specificationModel }}</view>
								</view>
								<view class="coll-item">
									<view class="name">设备编号： </view>
									<view class="value">{{ value.code }}</view>
								</view>
								<view class="coll-item">
									<view class="name">所属基地： </view>
									<view class="value">{{ value.stationName }}</view>
								</view>
								<checkbox :value="value.eventCostId +''" :checked="false" class="checkbox color round"></checkbox>
							</view>
						</label>
					</view>
				</checkbox-group>
				
				<view class="header" v-if="materialsData.length > 0">材料调度</view>
				<checkbox-group @change="materialChange">
					<view class="device"  v-for="item in materialsData" :key="item.name">
						<view class="title">
							<view class="name">{{ item.name }}</view>
							<view class="value">{{ item.totalNum }}</view>
						</view>
						<view class="coll" v-for="(value,v) in item.children" :key="v">
							<view class="coll-item">
								<view class="name">规格型号： </view>
								<view class="value model">{{ value.specificationModel }}</view>
							</view>
							<view class="coll-item">
								<view class="name">所属基地： </view>
								<view class="value">{{ value.stationName }}</view>
							</view>
							<view class="coll-item">
								<view class="name">出库量： </view>
								<view class="value">
									<!-- <uni-number-box :min="0" :max="value.costNum" v-model="value.costNum" :disabled="isShowInputNumber" @change="(cur)=>inputNumberChange(value,cur)"></uni-number-box> -->
									<u-number-box :min="0" :max="value.costNum" v-model="value.costNum"  @change="(cur)=>inputNumberChange(value,cur.value)" :disabled="isShowInputNumber" color="#323233"></u-number-box>
								</view> {{ value.unit }}
							</view>
							<checkbox :value="value.tempName" :checked="false" class="checkbox color round"></checkbox>
						</view>
					</view>
				</checkbox-group>
			</view>
		</scroll-view>
		<!-- <view class="fixedButton">
			<u-button type="primary"  :loading="loading" text="提交" @click="submit" :disabled="disabled"></u-button>
		</view> -->
		<view class="footer-button1">
			<view class="button-placeholder1"></view>
			<view class="button-group1">
				<button @click="submit" :loading="loading" :disabled="disabled" class="button-primary1">提交</button>
				<button @click="getBatchDelete" :loading="loading" :disabled="disabled" class="button-warn1">移除</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { getEventShoppingCartSubmit, getEventShoppingCartList, getShoppingCartBatchDelete, getShoppingCartBatchSave, getMaterialList, getShoppingCartMaterialList } from "@/api/emergency/emergencyDispatch.js"
	export default {
		name: "dispatchSheet",
		data() {
			return {
				loading: false,
				userData: [],      // 人员列表
				laborNum: "",      // 劳务人员数量
				deviceData: [],    // 设备列表
				materialsData: [], // 材料列表
				eventId: null,
				isDelete: false,
				isShowInputNumber: false,
				isLaborPerson: false,
				disabled: false,   // 是否禁用 提交按钮
			}
		},
		onLoad(option){
			if(!this.eventId){
				this.eventId = option.eventId
			}
		},
		mounted() {
			this.getList()
			this.getMaterialList()
		},
		methods:{
			// 获取购物车数据
			async getList(){
				let _data = { eventId : this.eventId }
				// 获取人员列表
				this.userData = []
				this.deviceData = []
				this.materialsData = []
				this.laborNum = ""
				let res = await getEventShoppingCartList(_data)
				this.userData = res.result.personList || []
				this.deviceData = this.arrayFilter(res.result.equipmentList, 'subDeviceTypeName') || []
				this.materialsData = res.result.materialList || []
				// 格式化 材料数据
				let mater = this.materialsData.filter(item => item.costNum !== 0)
				let temp = this.getMaterialArray(mater)
				this.materialsData = this.arrayFilter(temp[1].map(ele=>({...ele, tempName: ele.stationName + '-' + ele.name + "-" + ele.specificationModel})), "name")
				this.tempObjInfo = temp[0]
				this.laborNum = res.result.laborPerson ? res.result.laborPerson.num : ""
				this.laborPersonObj = res.result.laborPerson
				
				if(this.userData.length > 0 || this.deviceData.length > 0 || this.materialsData.length  > 0 || (this.laborNum !=="" && this.laborNum > 0)){
					this.disabled = false
				}else{
					this.disabled = true
				}
			},
			
			// 人员 多选框选择
			personChange(val){
				this.selectPersonList = val.detail.value.map(item => +item)
				console.log(this.selectPersonList);
			},
			
			// 设备 多选
			deviceChange(val){
				this.selectDeviceList = val.detail.value.map(item => +item)
				console.log(this.selectDeviceList);
			},
			
			// 材料 多选
			materialChange(val){
				this.selectMaterialList = val.detail.value
			},
			
			// 批量删除
			async getBatchDelete(){
				if(this.isDelete) return
				this.isDelete = true
				let list = []
				let materIds = []
				if(this.selectMaterialList && this.selectMaterialList.length > 0){
					this.selectMaterialList.forEach(ele => {
						this.tempObjInfo[ele].forEach(item=>{
							materIds.push(item.eventCostId)
						})
					});
				}
				console.log(materIds,'materIds');
				if(!this.selectPersonList){
					this.selectPersonList = []
				}
				if(!this.selectDeviceList){
					this.selectDeviceList = []
				}
				list = [...this.selectPersonList,...this.selectDeviceList,...materIds]
				if(list.length > 0){
					// 删除
					let res = await getShoppingCartBatchDelete(list)
					this.getList()
				}
				this.selectPersonList = []
				this.selectDeviceList = []
				this.selectMaterialList = []
				this.isDelete = false
			},
			
			// 劳务人员 change事件
			async laborNumBlur(value){
				if(this.isLaborPerson) return
				this.isLaborPerson = true
				console.log(value, this.laborNum);
				let obj = {type: "labor_person", num: this.laborNum, eventId: this.eventId}
				if(this.laborPersonObj && this.laborPersonObj.id){
					obj.id = this.laborPersonObj.id
				}
				let res = await getShoppingCartBatchSave([obj])
				await this.getList()
				this.isLaborPerson = false
			},
			
			// input-number change事件
			async inputNumberChange(val,cur){
				if(this.isShowInputNumber){
					return
				}
				this.isShowInputNumber = true
				let obj = {
					name: val.name,
					costNum2: cur,
					stationName: val.stationName,
					specificationModel: val.specificationModel,
				}
				// 先获取已经保存的 eventCostId
				let ids = this.tempMaterialList.filter(item=>obj.name === item.name && obj.stationName === item.stationName && obj.specificationModel === item.specificationModel).map(item=>item.eventCostId)
				console.log(ids);
				// 把保存的数据先先删除掉
				if(ids.length  > 0){
					let res = await getShoppingCartBatchDelete(ids)
					await this.getMaterialList()
				}
					
				let str = obj.stationName + '-' + obj.name + "-" + obj.specificationModel
				let list = this.sumArray(this.tempObj[str], obj.costNum2, "num")
				let arr = []
				list.forEach(item=>{
					if(item.num > 0){
						let obj = {
							itemId: item.id,
							type: "material",
							num: item.num,
							eventId: this.eventId,
						}
						arr.push(obj)
					}
				})
				// 再保存数据
				if(arr.length > 0){
					let res2 = await getShoppingCartBatchSave(arr)
					await this.getMaterialList()
					await this.getList()
				}else{
					await this.getList()
				}
				this.isShowInputNumber = false
			},
			
			
			// 返回上一级
			goBack(url){
				console.log(url,'链接');
				uni.navigateTo({
					url: `${url}?eventId=${this.eventId}`
				})
				// uni.navigateBack({
				// 	url: `${url}?eventId=${this.eventId}`,
				// 	success: ()=>{
				// 		var pages = getCurrentPages();
				// 		var currPage = pages[pages.length - 1] //当前页面
				// 		var prePage = pages[pages.length - 2] //上一个页面
				// 		prePage.$vm.getShoppingCartList()  //<-----传递的参数,还能传个对象过去
				// 	}
				// })
			},
			
			// 提交
			async submit(){
				this.loading = true
				let res = await getEventShoppingCartSubmit({ eventId : this.eventId,projectCascade:JSON.parse(uni.getStorageSync("diapatch-title")).projectCascade })
				this.loading = false
				if(res.success){
					uni.showToast({
						title: '保存成功',
						icon: "success"
					})
					this.getList()
					// let pageList = getCurrentPages()
					// pageList.forEach(item=>{
					// 	console.log(item.route);
					// })
					uni.navigateTo({
						url: `/subpackage-emergency/pages/eventDetails?eventId=${this.eventId}&isShow=${true}`
					})
				}
			},
			
			// 获取设备列表数据
			async getMaterialList(){
				let res = await getMaterialList({eventId: this.eventId, projectId:null})
				this.tempMaterialData = res.result
				await this.getSelectMaterial()
			},
			
			// 获取选中的材料
			async getSelectMaterial(){
				// 获取设备选中数据
				let mater2 = await getShoppingCartMaterialList({eventId: this.eventId})
				this.tempMaterialList = JSON.parse(JSON.stringify(mater2.result))
				let noExistList=[];//购物车与现有库存不重复的列表
				let cartMap={};// 购物车 唯一key 和出库量对应map
				let cartNoExistList=[]// 购物车与现有库存不存在key(去重)

				mater2.result.forEach(value=>{
					let key=value.name+value.stationName+value.specificationModel;//名称+基地+规格型号
					let itemNum=cartMap[key];
					if(!itemNum){
						itemNum=value.costNum
					}else{
						itemNum+=value.costNum
					}
					cartMap[key]=itemNum;
					let b=false;//购物车和库存列表是否重合
					this.tempMaterialData.forEach(item=>{
						if(item.name === value.name && item.stationName === value.stationName && item.specificationModel === value.specificationModel){
							item.num = item.num
							b=true;
						}
					})
					if(!b){
						value.num = value.costNum
						noExistList.push(value);
						if(!cartNoExistList.includes(key)){
							cartNoExistList.push(key);
						}
					}
				})
				this.tempMaterialData = [...noExistList, ...this.tempMaterialData]
				// 处理数据, 返回一个数组 数组第一项是 一个对象, 第二项是个数组(格式化好的)
				let temp = this.getMaterialArray(this.tempMaterialData)
				this.tableData2 = temp[1]
			
				for (let index = 0; index < this.tableData2.length; index++) {
					let keyIndex= this.tableData2[index].name+this.tableData2[index].stationName+this.tableData2[index].specificationModel;
					
					this.tableData2[index].costNum2=cartMap[keyIndex] ? cartMap[keyIndex] : 0; //购物车的出库数量
					if(cartNoExistList.length ==0 || !cartNoExistList.includes(keyIndex)){//购物车和库存列表是否重合
						this.tableData2[index].num+= cartMap[keyIndex]?cartMap[keyIndex]:0;//库存数量+购物车出库数量
					}
				}
				

				
				this.materialNameList = this.arrayFilter(this.tableData2, 'name')
				// 按照 基地名称排序 基地名称相同, 按照 材料名称排序, 材料名称相同 按照规格型号排序
				this.materialNameList.sort(function(val, item){
					return val.name.localeCompare(item.name, "zh-CN")
				})
				console.log(this.tableData2, this.materialNameList);
				this.tempObj = temp[0]
			},
			
			sumArray (list, initialValue, keyName){
				let sum = 0
				let obj = {
					find: null,
					index: null
				}
				for(let i = 0;i < list.length;i++) {
					let item = list[i]
					sum = sum + item[keyName]
					if(sum >= initialValue){
						obj.find = item
						obj.find[keyName] = item[keyName]-(sum - initialValue)
						obj.index = i
						break;
					}
				}
				return [...list.slice(0,obj.index), obj.find]
			},
			
			
			getMaterialArray(newArr){
				let list = JSON.parse(JSON.stringify(newArr))
				let obj = {}
				for(let i = 0;i < list.length;i++) {
					let item = list[i]
					let str = item.stationName + '-' + item.name + "-" + item.specificationModel
					if(obj[str]){   
						obj[str].push(item)
					}else{
						obj[str] = []
						obj[str].push(item)
					}
				}
	
				let newList = []
				for (const key in obj) {
					let arr = obj[key]
					let num = 0
					for(let i = 0;i < arr.length;i++) {
						num = num +  +arr[i].costNum
					}
					let temp = {
						stationName: arr[0].stationName,
						name:  arr[0].name,
						specificationModel: arr[0].specificationModel,
						costNum: num,
						unit: arr[0].unit || "",
						// costNum2: 0,
					}
					newList.push(temp)
				}
				return [obj, newList]
			},
			
			/**
			* @description:  list 数组根据 stationName分组 num统计数量
			* @param {type}  list: 需要处理的数组  (原数组)
			* @param {type}  stationName: 用于判断相同的键名 
			* @return:       返回值: 数组
			*/
			arrayFilter(list, stationName){
				let obj = {}
				let newList = []
				for (let i = 0; i < list.length; i++) {
					let item = list[i]
					let str = item[stationName]
					if(obj[str]){
						obj[str].push(item)
					}else{
						obj[str]=[]
						obj[str].push(item)
					}
				}
				// 对象转数组
				if(stationName === "name"){
					for (let key in obj) {
						let value = obj[key]
						let totalNum = 0
						let unit = ""
						value.forEach(item=>{
							totalNum = totalNum + item.costNum
							unit = item.unit
						})
						let newkey = {name: key, totalNum:totalNum+unit, children: value}
						newList.push(newkey)
					}
				}else{
					for (let key in obj) {
						let value = obj[key]
						let newkey = {name: key, num:value.length, children: value}
						newList.push(newkey)
					}
				}
				
				return newList
			}
		}
	}
</script>

<style lang="scss" scoped>
	page{
		height: 100%;
		width: 100%;
	}
	body{
		width: 100%;
		height: 100%;
	}
	.dispatchSheet{
		position: relative;
		margin-top: 30rpx;
		width: 100%;
		height: calc(100vh - 30rpx);
		/* #ifdef MP-WEIXIN */
			padding-top: 160rpx;
		/* #endif */
		
		.del{
			// position: absolute;
			// top: 48rpx;
			// right: 50rpx;
			font-size: 36rpx;
			color: #3180e4;
		}
		.scroll-box{
			max-height: calc(100vh - 252rpx);
			padding-top: 10rpx;
		}
		.content{
			padding: 24rpx 32rpx;
			padding-top: 0rpx;
			height: calc(100vh - 300rpx);
		}
		.header{
			line-height: 120rpx;
			height: 120rpx;
			background-color: #F5F7FA;
			font-size: 36rpx;
			font-family: Noto Sans KR-Bold, Noto Sans KR;
			font-weight: bold;
			color: #445469;
			padding-left: 30rpx;
		}
		.person{
			padding: 0rpx 32rpx;
			.nav-item{
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 120rpx;
				line-height: 120rpx;
				border-bottom: 2rpx solid #E2E5ED;
				.name{
					font-size: 32rpx;
					font-weight: 500;
					color: #445469;
				}
				.input{
					width: 360rpx;
					font-size: 32rpx !important;
				}
				.personNum{
					margin-right: 20rpx;
					font-size: 32rpx;
					font-weight: bold;
					color: #22204E;
				}
			}
			.col-item{
				.label{
					display: flex;
					align-items: center;
					justify-content: space-between;
					height: 120rpx;
					line-height: 120rpx;
					border-bottom: 2rpx solid #E2E5ED;
					padding: 0rpx 40rpx;
					.name{
						// margin-right: 45rpx;
						max-width: 260rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap
					}
					.value {
						max-width: 240rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
					.phone{
						flex: 1;
					}
				}
			}
		}
		
		.device{
			padding: 0rpx 32rpx;
			.title{
				display: flex;
				line-height: 120rpx;
				height: 120rpx;
				align-items: center;
				justify-content: space-between;
				font-size: 32rpx;
				font-weight: 600;
				color: #445469;
				border-bottom: 2rpx solid #E2E5ED;
				.name{
					// margin-right: 45rpx;
					// max-width: 260rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap
				}
				.value{
					margin-right: 25rpx;
					max-width: 240rpx;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}
			}
			.coll{
				position: relative;
				padding-bottom: 20rpx;
				border-bottom: 2rpx solid #E2E5ED;
				.coll-item{
					padding: 0rpx 20rpx;
					margin-top: 20rpx;
					display: flex;
					align-items: center;
					
					.name{
						margin-left: 25rpx;
						// width: 240rpx;
					}
				}
				.checkbox{
					position: absolute;
					top: 10rpx;
					right: 20rpx;
				}
			}
		}
	}
	::v-deep .uni-numbox__value{
		background-color: #fff !important;
		border: 2rpx solid #E2E5ED;
		margin: 0;
	}
	::v-deep .navBar{
		margin: 0rpx;
		padding-top: 30rpx;
	}
	::v-deep .navBar .left{
		top: 44rpx;
	}
	.footer-button1 {
		height: 240upx;
		
		.button-placeholder1 {
			height: 100%;
		}
		
		.button-group1 {
			// display: flex;
			height: 240upx;
			padding: 30upx; 
			box-sizing: border-box; 
			background: #fff; 
			position: fixed; 
			width: 100%; 
			bottom: 0; 
			z-index: 11;
			
			.button-primary1 {
				background: #2f80ed; 
				border-radius: 4upx; 
				color: #fff; 
				font-weight: bold; 
				line-height: 92upx; 
				text-align: center;
				width: 100%;
			}
			.button-warn1 {
				margin-top: 10rpx;
				background: #ff6a6a; 
				border-radius: 4upx; 
				color: #fff; 
				font-weight: bold; 
				line-height: 92upx; 
				text-align: center;
				width: 100%;
			}
		}
	}
	.value.model {
		max-width: 340rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
</style>